(function(window) {
	var $ = window.$,
		Vue = window.Vue,
		echarts = window.echarts;

	var size = {
		height: '100%',
		width: '100%'
	};

	var defaults = {
		tooltip: {
			show: false
		},
		toolbox: {
			show: false
		}
	};

	var events = [
		'click',
		'dblclick',
		'mouseover',
		'mouseout',
		'mousedown',
		'mouseup',
		'globalout'
	];

	var methods = [
		'dispatchAction',
		'showLoading',
		'hideLoading',
		'getWidth',
		'getHeight',
		'getOption',
		'clear'
	];

	var factory = {
		props: ['options', 'width', 'height'],
		template: '<div></div>',
		data: function() {
			return {
				chart: null,
				_resize: null
			};
		},
		mounted: function() {
			if(this.options) {
				this._init();
			}
		},
		watch: {
			options: {
				handler: function(options) {
					if(!this.chart && options) {
						this._init()
					} else {
						setTimeout(function() {
							this.chart.setOption($.extend(true, {}, defaults, this.options), true);
						}.bind(this));
					}
				},
				deep: true
			}
		},
		methods: {
			_init: function() {
				if(this.chart) return;
				var me = this;
				this.$el.style.width = this.width || size.width;
				this.$el.style.height = this.height || size.height;
				var chart = echarts.init(this.$el); //  初始化echarts组件
				chart.setOption($.extend(true, {}, defaults, this.options), true);
				//	添加随着窗口变化自动监听
				this._resize = chart.resize;
				window.addEventListener('resize', this._resize);
				//	添加事件
				events.forEach(function(e) {
					chart.on(e, function(params) {
						me.$emit(e, params);
					});
				});
				//  挂载chart
				this.chart = chart;
			},
			resize: function() {
				this.chart && this.chart.resize();
			}
		},
		beforeDestroy: function() {
			if(!this.chart) return;
			window.removeEventListener('resize', this._resize);
			this.chart.dispose();
			this.chart = null;
			this._resize = null;
		}
	};

	/**
	 * 添加echarts的方法
	 */
	methods.forEach(function(m) {
		factory.methods[m] = function() {
			return this.chart[m].apply(this.chart, [].slice.apply(arguments));
		};
	});

	Vue.component('chart', factory);
})(window);